package com.aiss.ws.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;


import com.aiss.ws.MyApplication;
import com.aiss.ws.R;

import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.sharedpreferences.Pref;

/**
 * Created by chenqiang on 15/12/26.
 */
@EActivity
public class BaseActivity extends FragmentActivity {

    private int tid;
    private Handler handler;
    private LayoutInflater inflater;
    private ProgressDialog loadingViewDialog;
    private long lastToastTime;
    private String lastToastText;
    private static final long TOAST_INTERNAL = 2000;
    private static Context context;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.getInstance().addActivity(this);
        context =this;
        tid = Process.myTid();
        handler = new Handler();
        inflater = LayoutInflater.from(this);
    }

    /**
     * 跳转activity
     * @param clazz
     */
    public void startActivity(Class<?extends Activity> clazz){
        startActivity(new Intent(context,clazz));
    }


    public void showMessagefail(){
        showMessage("网络异常");
    }

    private Toast toast;
    public void showMessage(final String content){
        handler.post(new Runnable() {
            @Override
            public void run() {

                if(toast==null){
                    toast = Toast.makeText(context,content, Toast.LENGTH_SHORT);
                }else{
                    toast.cancel();
                    toast = Toast.makeText(context,content, Toast.LENGTH_SHORT);
                }
                toast.show();

            }
        });

    }


    public void showConfirmDialog(String text, final OnDialogConfirmListener listener) {
        new AlertDialog.Builder(this).setMessage(text)
                .setTitle(getString(R.string.dialog1))
                .setPositiveButton(getString(R.string.dialog2), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        listener.onDialogConfirm();
                    }
                }).setNegativeButton(getString(R.string.dialog3), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create().show();
    }

    public void showToastSafe(final String text) {

        if (text == null)
            return;
        if ((System.currentTimeMillis() - lastToastTime) < TOAST_INTERNAL && text.equals(lastToastText))
            return;
        if (tid == Process.myTid()) {
            Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
        } else {
            post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(BaseActivity.this, text, Toast.LENGTH_SHORT).show();
                }
            });
        }
        lastToastTime = System.currentTimeMillis();
        lastToastText = text;
    }

    public void showToastSafe(int id) {
        showToastSafe(getString(id));
    }

    public void showLoading() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (isValidContext(BaseActivity.this)) {
                    if (loadingViewDialog == null) {
                        loadingViewDialog = new ProgressDialog(BaseActivity.this);
                        loadingViewDialog.setCanceledOnTouchOutside(false);
                    }
                    loadingViewDialog.setMessage(getString(R.string.loading));
                    loadingViewDialog.show();
                }
            }
        });

    }

    public void hideLoading() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (isValidContext(BaseActivity.this)) {
                    if (loadingViewDialog != null && loadingViewDialog.isShowing()) {
                        loadingViewDialog.hide();
                    }
                }
            }
        });
    }

    protected boolean isValidContext(Activity a) {
        if (Build.VERSION.SDK_INT >= 17) {
            if (a.isDestroyed() || a.isFinishing()) {
                return false;
            } else {
                return true;
            }
        } else {
            if (a.isFinishing()) {
                return false;
            } else {
                return true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().removeActivity(this);
        handler.removeCallbacksAndMessages(null);
        if (loadingViewDialog != null) {
            loadingViewDialog.dismiss();
            loadingViewDialog = null;
        }
    }

    public boolean isInMainThread() {
        return tid == Process.myTid();
    }

    public void post(Runnable r) {
        handler.post(r);
    }

    public void postDelay(Runnable r, long time) {
        handler.postDelayed(r, time);
    }

    public View inflate(int id) {
        return inflater.inflate(id, null);
    }

    public int dip2px(float dipValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public int px2dip(float pxValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public interface OnDialogConfirmListener {
        void onDialogConfirm();
    }

    public static Context getContext (){
        return context;
    }
}
